<?php declare(strict_types=1);

namespace app\admin\controller;

use app\admin\Diluma;
use app\admin\service\WeblinkService;
use think\facade\Response;
use think\facade\View;
use think\facade\Log;

class Weblink extends Diluma
{
    /**
     * 首页
     * @return view
     */
    public function index()
    {
        return View::fetch();
    }

    /**
     * 列表数据
     * @return \think\response\Json
     */
    public function getWeblinkList(): \think\response\Json
    {
        $pageSize = (int)$this->request->param('page_size', 10);

        $service = new WeblinkService();
        $items = $service->getWeblinkList($pageSize);

        return json(['code'=>0, 'count'=>$items->total(), 'data'=>$items->items()]);
    }

    /**
     * 添加
     * @return mixed|Json
     * */
    public function insert(){
        $service = new WeblinkService();
        $post = $this->request->post();
        $data = [
            'name' => $post['name'],
            'link_url' => $post['link_url'],
        ];
        return $service->updateOrInsert($data);
    }

    /**
     * 编辑
     * @return string|\think\response\Json
     */
    public function edit()
    {
        $service = new WeblinkService();
        $post = $this->request->post();
        if(empty($post['id'])){
            return json(['code'=>1, 'msg'=>'参数异常']);
        }
        return $service->updateOrInsert($post);
    }

    /**
     * 删除
     * @return \think\response\Json
     */
    public function delete(){
        $id = $this->request->param('id');
        if(!$id){
            return json(['code'=>1, 'msg'=>'参数异常']);
        }
        try {
            $service = new BannerService();
            $service->delete($id);
            return json(['code'=>0, 'msg'=>'删除成功']);
        } catch (\Exception $e) {
            Log::error('delete error:'. $e->getMessage());
            return json(['code'=>1, 'msg'=>$e->getMessage()]);
        }
    }
}